package com.myapp.ruyixing.ui;

import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.http.TrainSearchListParser.TrainSearch;
import com.myapp.ruyixing.http.TrainSearchListParser.TrainSearchItem;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.TimeUtils;

public class TrainTicketSearchResultActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {

	ListView mListView;
	TextView mEmptyView;

	ToggleButton mFocusedTabView;
	TextView mDateView;
	private View mLoadingView;

	String mFromCity;
	String mToCity;
	String mStartDate;
	int mTrainType;
	int mTicketType;
	int mStartTime;
	int mEndTime;
	int mTimeSort;
	int mPriceSort;

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			TrainSearch t = (TrainSearch) o;

			if (t != null && t.items != null) {
				MyListAdapter adapter = new MyListAdapter(t.items);
				mListView.setAdapter(adapter);
				mListView.setEmptyView(mEmptyView);
				hideLoading();
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
			hideLoading();
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_train_ticket_search_result);

		initView();

		mFromCity = getIntent().getStringExtra("from");
		mToCity = getIntent().getStringExtra("to");
		mStartDate = getIntent().getStringExtra("date");
		mTrainType = getIntent().getIntExtra("traintype", 0);
		mTicketType = getIntent().getIntExtra("tickettype", 0);

		((TitleBar) findViewById(R.id.title_bar)).setTitleText(mFromCity + "-"
				+ mToCity);

		reqeust();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cost_price:
			mPriceSort = mPriceSort == 0 ? 1 : mPriceSort == 1 ? 2 : 1;
			mTimeSort = 0;
			changeFocusedTab(v, mPriceSort == 2);

			reqeust();

			break;
		case R.id.cost_time:
			mTimeSort = mTimeSort == 0 ? 1 : mTimeSort == 1 ? 2 : 1;
			mPriceSort = 0;
			changeFocusedTab(v, mTimeSort == 2);

			reqeust();

			break;
		case R.id.previous_day:
			changeDate(-1);
			break;
		case R.id.next_day:
			changeDate(1);

			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (position >= 0 && position < mListView.getAdapter().getCount()) {
			TrainSearchItem item = (TrainSearchItem) mListView.getAdapter()
					.getItem(position);
			item.date = mStartDate;
			startActivityForResult(new Intent(this,
					TrainTicketSubmitActivity.class).putExtra("data", item), 0);
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

		if (arg1 == RESULT_OK) {
			setResult(RESULT_OK);
			finish();
		}
	}

	private void showLoading() {
		mLoadingView.setVisibility(View.VISIBLE);
	}

	private void hideLoading() {
		mLoadingView.setVisibility(View.GONE);
	}
	
	private void reqeust() {
		showLoading();
		RYHttpClient.getTrains(this, mHandler, mFromCity, mToCity, mStartDate,
				mTrainType, mTicketType, mStartTime, mEndTime, mTimeSort,
				mPriceSort);
	}

	private void changeDate(int gap) {
		Calendar calendar = TimeUtils.parsrDate(mDateView.getText().toString());
		mDateView.setText(TimeUtils.getDayString(calendar, gap));
	}

	private void initView() {
		mListView = (ListView) findViewById(android.R.id.list);
		mEmptyView = (TextView) findViewById(android.R.id.empty);
		mLoadingView = findViewById(R.id.my_loading);

		mListView.setOnItemClickListener(this);

		findViewById(R.id.cost_sort).setOnClickListener(this);
		findViewById(R.id.cost_price).setOnClickListener(this);
		findViewById(R.id.cost_time).setOnClickListener(this);

		findViewById(R.id.previous_day).setOnClickListener(this);
		findViewById(R.id.next_day).setOnClickListener(this);
		mDateView = (TextView) findViewById(R.id.date);
		mDateView.setText(TimeUtils.getDayString(Calendar.getInstance()));

		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});
	}

	private void changeFocusedTab(View v, boolean selected) {
		if (mFocusedTabView != v) {
			if (mFocusedTabView != null) {
				mFocusedTabView.setChecked(false);
				mFocusedTabView.setSelected(false);
				setAsc();
			}
		}

		mFocusedTabView = (ToggleButton) v;
		mFocusedTabView.setChecked(true);
		if (selected) {
			setDsc();
		} else {
			setAsc();
		}
	}

	private void setDsc() {
		Drawable suggetionDrawable = getResources().getDrawable(
				R.drawable.icon_air_ticket_08_down);
		mFocusedTabView.setCompoundDrawablesWithIntrinsicBounds(
				null, null, suggetionDrawable, null);
	}

	private void setAsc() {
		Drawable suggetionDrawable = getResources().getDrawable(
				R.drawable.icon_air_ticket_08);
		mFocusedTabView.setCompoundDrawablesWithIntrinsicBounds(
				null, null, suggetionDrawable, null);
	}

	private class ViewHolder {
		TextView mStartTimeView;
		TextView mArriveTimeView;
		TextView mTimeView;
		TextView mFromView;
		TextView mToView;
		TextView mTrainView;
		TextView mPriceView;
		TextView mSeatView;
	}

	private class MyListAdapter extends ArrayAdapter<TrainSearchItem> {

		public MyListAdapter(List<TrainSearchItem> airlines) {
			super(TrainTicketSearchResultActivity.this, -1, airlines);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext())
						.inflate(R.layout.cell_train_ticket_search_result,
								parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mStartTimeView = (TextView) convertView
						.findViewById(R.id.start_time);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.price);
				holder.mArriveTimeView = (TextView) convertView
						.findViewById(R.id.arrive_time);
				holder.mFromView = (TextView) convertView
						.findViewById(R.id.from);
				holder.mToView = (TextView) convertView.findViewById(R.id.to);
				holder.mTrainView = (TextView) convertView
						.findViewById(R.id.train);
				holder.mTimeView = (TextView) convertView
						.findViewById(R.id.time);
				holder.mSeatView = (TextView) convertView
						.findViewById(R.id.seat);

				convertView.setTag(holder);
			}

			ViewHolder mHolder = (ViewHolder) convertView.getTag();

			TrainSearchItem item = getItem(position);

			mHolder.mStartTimeView.setText(item.starttime);
			mHolder.mPriceView.setText("￥" + item.ticketprice);
			mHolder.mArriveTimeView.setText(item.endtime);
			mHolder.mFromView.setText(item.startcity);
			mHolder.mToView.setText(item.endcity);
			mHolder.mTrainView.setText(item.trainname + item.traincode);
			mHolder.mTimeView.setText(item.coattime);
			mHolder.mSeatView.setText(item.ticketname);

			return convertView;

		}
	}
}
